// pages/stores/stores.js
Page({
    /**
     * 页面的初始数据
     */
    data: {
      user:'',
      users:[],
      userName:null,
      collected:false,
      _id:null,
      _storeId:null,
      storeName:null,
      state:'点菜',
      states:['点菜','店铺'],
      foods:[],
      storeDetail:{},
      total:0
    },
    // 选择显示点菜面板
    choosediancaiHandler(){
      this.setData({state:this.data.states[0]})
    },
    // 选择显示店铺面板
    choosestoreHandler(){
      this.setData({state:this.data.states[1]})
    },
    // 点击收藏店铺
    collectHandler(e){
      let user = this.data.user
      let users = this.data.users
      let userName = this.data.userName
      let _sId = this.data._storeId
      let collecteds = wx.getStorageSync('collecteds')
      if (userName==-1) {
        users.push(user)
        this.setData({
          users:users
        })
        this.yunUpdateCollect('CR_stores',_sId,this.data.users)
        this.yunGetDetailByName(this.data.storeName)
        if (collecteds) {
          collecteds.push(this.data.storeDetail)
          wx.setStorageSync('collecteds', collecteds)
        }
      }else{
        let i = users.indexOf(user)
        users.splice(i,1)
        this.yunUpdateCollect('CR_stores',_sId,this.data.users)
        this.yunGetDetailByName(this.data.storeName)

        if (collecteds) {
          let idx = collecteds.indexOf(this.data.storeDetail)
          collecteds.splice(idx,1)
          wx.setStorageSync('collecteds', collecteds)
        }
      }
    },
    // 跳转到菜品详情页面
    todetails(e){
      let foodDetail = e.currentTarget.dataset.item
      wx.navigateTo({
        url: '/pages/details/details?foodName='+foodDetail.foodName+'&&num='+foodDetail.num
      })
    },
    // 减少菜品数量
    numReduceHandler(e){
      if (e.currentTarget.dataset.item.num>0) {
        let id = e.currentTarget.dataset.item._id
        this.yunUpdate('CR_foods',id,e.currentTarget.dataset.item.num-1)
        setTimeout((res)=>{
          this.getTotal()
        },500)
      }
    },
    // 添加菜品数量
    numAddHandler(e){
      let _id = e.currentTarget.dataset.item._id
      let num = e.currentTarget.dataset.item.num
      num = parseInt(num)+1
      this.yunUpdate('CR_foods',_id,num)
      setTimeout((res)=>{
        this.getTotal()
      },500)
      
    },
    // 点击加入订单
    payHandler(){
      let that = this
      let order = this.data.foods.filter(function(item){
        return item.num>0
      })
      if (order[0]) {
        wx.setStorageSync('order', order)
        wx.navigateTo({
          url: '/pages/toPay/toPay?storeName='+that.data.storeName
        })
      }else{
        wx.showToast({
          title: '请选择商品',
          duration: 1500,
          icon: 'error'
        })
      }
    },
    yunGetFoodByName(data){
      //云数据根据店铺名称查询food表
      let db = wx.cloud.database()
      let that = this
      db.collection('CR_foods')
      .where({store:data})
      .get({
        success:(res)=>{
          that.setData({
            foods:res.data
          })
            this.getTotal()
        }
      })
    },
    yunGetDetailByName(data){
      //云数据根据店铺id查询店铺表
      let db = wx.cloud.database()
      let that = this
      db.collection('CR_stores')
      .where({storeName:data})
      .get({
        success:(res)=>{
          that.setData({
            storeDetail:res.data[0],            
            users:res.data[0].collected,
            _storeId:res.data[0]._id,
            user:wx.getStorageSync('Tel')
          })
          setTimeout((res)=>{
            this.data.userName = this.data.users.indexOf(that.data.user)
            if (this.data.userName==-1) {
              this.setData({
                collected:false
              })
            }else{
              this.setData({
                collected:true
              })
            }
          },500)
        }
      })
    },
    // 修改菜品数量
    yunUpdate(table,id,num){
      let db = wx.cloud.database()
      let that = this
      db.collection(table)
      .doc(id)
      .update({
        data:{
          num:num
        },success:(res)=>{
          this.yunGetFoodByName(that.data.storeName)
        }
      })
    },
    // 修改店铺收藏
    yunUpdateCollect(table,id,users){
      let db = wx.cloud.database()
      let that = this
      db.collection(table)
      .doc(id)
      .update({
        data:{
          collected:users
        },success:(res)=>{
          this.yunGetDetailByName(that.data.storeName)
          if (!that.data.collected) {
            this.setData({
              collected:true
            })
          }else{
            that.setData({
              collected:false
            })
          }
        }
      })
    },
    // 计算总价
    getTotal(){
      var all = 0
      for (var i of this.data.foods) {
        all+=i.price*i.num
        this.setData({total:all})
      }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      if (options.num) {
        this.yunUpdate('CR_foods',options._id,options.num)
      }
      this.setData({storeName:options.storeName})
      this.yunGetFoodByName(this.data.storeName)
      this.yunGetDetailByName(this.data.storeName)
    },
    
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
      for (var i of this.data.foods) {
        this.yunUpdate('CR_foods',i._id,0)
      }
    },
    
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
      for (var i of this.data.foods) {
        this.yunUpdate('CR_foods',i._id,0)
      }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
      this.onLoad()
      wx.showToast({
        title: '刷新成功！',
        duration: 800,
        icon:'none'
      })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
      wx.showToast({
        title: '已经到底啦>_<',
        duration: 800,
        icon: 'none'
      })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})